package com.teradata.observer.core;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 事件 注册 监听 器
 * Created by lyndon on 2018/5/29.
 */
public class EventListener {

    protected Map<Enum, Event> events = new HashMap<Enum, Event>();

    public void addListener(Enum eventType, Object target, Method callback){

        // 注册事件
        // 用反射调用该方法
        events.put(eventType, new Event(target, callback));
    }

    private void trigger(Event event){
        event.setSource(this);
        event.setTriggerTime(System.currentTimeMillis());

        try {
            event.getCallback().invoke(event.getTarget(), event);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }



    protected void trigger(Enum call){
        if (!this.events.containsKey(call)){
            return ;
        }

        // 触发 内部方法
        trigger(this.events.get(call).setTrigger(call.toString()));

    }

}
